﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using AdvCMS.Models;
using AdvCMS.Data.Repositories;
using AdvCMS.Factory;
using AdvCMS.Data;
using PagedList;

namespace AdvCMS.Controllers
{
    // Live In BNE : http://www.liveinbne.info 
    // Brisbane Life Style News
    [HandleError]
    public class AccountController : BaseController
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        private IUserRepository userRepository;

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
            Factory.RepositoryFactory factory = new RepositoryFactory();
            userRepository = factory.NewUserRepository();
            base.Initialize(requestContext);
        }

        [Authorize]
        public ActionResult List(int? page)
        {
            IList<IAdvUser> users = userRepository.FindAll();

            var pageNumber = page ?? 1;
            var onePageOfUsers = users.ToPagedList(pageNumber, 25);

            ViewBag.OnePageOfUsers = onePageOfUsers;
            return View();
           
        }

        [Authorize]
        // https://play.google.com/store/apps/details?id=com.advgen.AdvNetInfoPro - Android Network Tools
        // Edit/Create a user
        public ActionResult EditUser(int? id)
        {
            IAdvUser user = userRepository.Create();
            if (id.HasValue)
            {
                user = userRepository.Get(id.Value);
            }
          
            return View(user);
        }

        [Authorize]
        public ActionResult Delete(int id)
        {
            IAdvUser user =userRepository.Get(id);
            userRepository.Delete(user);
            userRepository.Update();

            TempData["Message"] = "The record is deleted";
            return RedirectToAction("List");
        }

         [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditUser(int? id, string username, string password, string email, string comment,bool isApproved , bool isLockedout)
        {
            IAdvUser user = userRepository.Create();
            if (id.HasValue && id != 0)
            {
                user = userRepository.Get(id.Value);
            }
          

            user.Username = username;
            if (password != user.Password)
            {
                user.LastPasswordChangedDate = DateTime.Now;
            }
            user.Password = password;
            user.Email = email;
            user.Comment = comment;
            user.IsApproved = isApproved;
            user.IsLockedOut = isLockedout;
            if (user.Id == 0)
            {
                userRepository.Insert(user);
            }
            userRepository.Update();
            
            return View(user);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }
      
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
